/**
 * 用户信息管理工具
 */

// 用户信息存储键名
const USER_INFO_KEY = 'user_info';

// 用户信息接口
export interface UserInfo {
  id?: string | number;
  name?: string;
  nickname?: string;
  username?: string;
  avatar?: string;
  role?: string;
  roles?: string[];
  permissions?: string[];
  lastUpdated?: number;
}

/**
 * 保存用户信息到本地存储
 */
export const saveUserInfoToStorage = (userInfo: UserInfo): void => {
  try {
    const userInfoWithTimestamp = {
      ...userInfo,
      lastUpdated: Date.now()
    };
    localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfoWithTimestamp));
    console.log('[UserInfo] 用户信息已保存到本地存储:', userInfoWithTimestamp);
  } catch (error) {
    console.error('[UserInfo] 保存用户信息到本地存储失败:', error);
  }
};

/**
 * 从本地存储获取用户信息
 */
export const getUserInfoFromStorage = (): UserInfo | null => {
  try {
    const userInfoStr = localStorage.getItem(USER_INFO_KEY);
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr) as UserInfo;
      console.log('[UserInfo] 从本地存储获取用户信息:', userInfo);
      return userInfo;
    }
  } catch (error) {
    console.error('[UserInfo] 从本地存储获取用户信息失败:', error);
  }
  return null;
};

/**
 * 清除本地存储的用户信息
 */
export const clearUserInfoFromStorage = (): void => {
  try {
    localStorage.removeItem(USER_INFO_KEY);
    console.log('[UserInfo] 已清除本地存储的用户信息');
  } catch (error) {
    console.error('[UserInfo] 清除本地存储用户信息失败:', error);
  }
};

/**
 * 检查用户信息是否过期（可选功能）
 * @param maxAge 最大缓存时间（毫秒），默认 30 分钟
 */
export const isUserInfoExpired = (maxAge: number = 30 * 60 * 1000): boolean => {
  const userInfo = getUserInfoFromStorage();
  if (!userInfo || !userInfo.lastUpdated) {
    return true;
  }
  
  const now = Date.now();
  const isExpired = (now - userInfo.lastUpdated) > maxAge;
  
  if (isExpired) {
    console.log('[UserInfo] 用户信息已过期，需要重新获取');
    clearUserInfoFromStorage();
  }
  
  return isExpired;
};

/**
 * 获取用户显示名称（从原始API数据结构中获取）
 */
export const getUserDisplayName = (userInfo: any): string => {
  if (!userInfo) return '未登录';
  
  // 如果数据结构是 { user: {...}, roles: [...], permissions: [...] }
  if (userInfo.user) {
    const user = userInfo.user;
    // 兼容不同后端字段命名：nickname/nickName，username/userName，id/userId
    const nick = user.nickname || user.nickName;
    const name = user.name;
    const uname = user.username || user.userName;
    const uid = user.id || user.userId;

    if (nick) return nick;
    if (name) return name;
    if (uname) return uname;
    if (uid) return `用户${uid}`;
  }
  
  // 如果数据结构是扁平的 { id, name, nickname, username, ... }
  const nick = userInfo.nickname || userInfo.nickName;
  const uname = userInfo.username || userInfo.userName;
  const uid = userInfo.id || userInfo.userId;
  if (nick) return nick;
  if (userInfo.name) return userInfo.name;
  if (uname) return uname;
  if (uid) return `用户${uid}`;
  
  return '未登录';
};
